package com.sq.springbootvue.shiro;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sq.springbootvue.entity.User;
import com.sq.springbootvue.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @program: vue-element-template-backend
 * @description:
 * @author: 翁仕权
 * @create: 2020-06-27 17:15
 */
public class UserRealm extends AuthorizingRealm {


    /**
     * 执行授权逻辑
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
        System.out.println("执行授权逻辑");

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//        info.addStringPermission("user:add");
        //拿到当前登录的这个对象
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User) subject.getPrincipal();//拿到User对象

        //设置当前用户的权限
        info.addStringPermission(currentUser.getPerms());

        return info;
    }

    @Autowired
    private UserService userSerivce;

    /**
     * 执行认证逻辑
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行认证逻辑");

        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户的登录数据


        //编写shiro判断逻辑，判断用户名和密码
        //1.判断用户名
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
        queryWrapper.lambda().eq(User::getName, userToken.getUsername());
        User user = userSerivce.getOne(queryWrapper);

        if (user == null) {
            //用户名不存在
            return null;//shiro底层会抛出UnKnowAccountException
        }

        //可以加密  MD5 MD5盐值加密
        //2.密码认证  （获取当前用户认证，传递密码对象，认证名）
        return new SimpleAuthenticationInfo(user, user.getPassword(), "");
    }

}
